package com.fishingwithme.infrastructure;

import com.fishingwithme.domain.user.UserService;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.Map;
import java.util.Objects;

@Component
class WeChatService {

    @Value("${wechat.appId}")
    private String APP_ID;

    @Value("${wechat.appSecret}")
    private String APP_SECRET;

    private static final String WECHAT_LOGIN_URL = "https://api.weixin.qq.com/sns/jscode2session";
    private static final Logger logger = LoggerFactory.getLogger(WeChatService.class);
    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired
    private UserService userService;

    public WeChatUserInfo getUserInfoByCode(String code) {
        String url = String.format("%s?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code",
                WECHAT_LOGIN_URL, APP_ID, APP_SECRET, code);

        try {
            String response = restTemplate.getForObject(url, String.class);
            ObjectMapper objectMapper = new ObjectMapper();
            Map json = objectMapper.readValue(response, Map.class);

            // 检查是否有错误
            if (json.containsKey("errcode")) {
                int errorCode = (int) json.get("errcode");
                if (errorCode != 0) {
                    String errorMsg = json.get("errmsg").toString();
                    logger.error("微信登录错误: {} - {}", errorCode, errorMsg);
                    throw new WeChatLoginException("微信登录失败: " + errorMsg, errorCode);
                }
            }

            // 获取用户信息
            String openId = json.get("openid").toString();
            String sessionKey = json.get("session_key").toString();

            if (StringUtils.isBlank(openId) || StringUtils.isBlank(sessionKey)) {
                return null;
            }

            WeChatUserInfo userInfo = new WeChatUserInfo();
            userInfo.setOpenId(openId);
            userInfo.setSessionKey(sessionKey);
            if (!Objects.isNull(json.get("unionid"))) {
                userInfo.setUnionId(json.get("unionid").toString());
            }

            // 缓存sessionKey用于解密
            //redisTemplate.opsForValue().set(CACHE_KEY_WECHAT_SESSION + openId, sessionKey, 30, TimeUnit.MINUTES);

            return userInfo;
        } catch (Exception e) {
            logger.error("获取微信用户信息失败", e);
            return null;
        }
    }

}
